package com.jrx.anytxn.transaction.job.interestFile.config;

import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.config.InterestFileConfig;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.job.interestFile.step.MergeInterestFileListener;
import com.jrx.anytxn.transaction.service.IInterestFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(InterestFileConfig.class)
public class MergeInterestFileConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(MergeInterestFileConfiguration.class);

    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    private InterestFileConfig interestFileConfig;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private IInterestFileService interestFileService;
    @Autowired
    private MergeInterestFileListener mergeInterestFileListener;

    @Bean
    public Job mergeInterestFileJob(){
        return jobBuilderFactory.get("mergeInterestFileJob").incrementer(new RunIdIncrementer()).listener(mergeInterestFileListener)
                .start(mergeInterestFileStep())
                .build();
    }

    @Bean
    public Step mergeInterestFileStep() {
        return stepBuilderFactory.get("mergeInterestFileStep")
                .tasklet(mergeInterestFileTasklet())
                .build();
    }

    @Bean
    @StepScope
    public Tasklet mergeInterestFileTasklet() {
        return (stepContribution, chunkContext) -> {
            logger.debug("分库文件合并开始。。。。。。");
            String filePath = interestFileConfig.getInterestFilePath();
            String fileName = interestFileConfig.getInterestFileName();

            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
            interestFileService.mergeFile(org,filePath,fileName);

            logger.debug("报送分库文件合并处理完成");
            return RepeatStatus.FINISHED;
        };
    }
}
